// -*-mode:c++; coding:utf-8-*-

#include <sstream>

#include "sstable_block_cache_base.hpp"

namespace xbase
{

	std::string cache_key::to_string() const
	{
		std::ostringstream out;
		out << "{file_id: " << m_file_id
		    << "; block_index: " << m_block_index
		    << "}";
		return out.str();
	}

	std::string cache_value::to_string() const
	{
		std::ostringstream out;
		out << "{ref_count: " << m_ref_count
		    << "; block_size: " << m_block_size
		    << "; block_entry_number: " << m_block_index.size()
		    << "}";
		return out.str();
	}

	std::string cache_node::to_string() const
	{
		std::ostringstream out;
		out << "{key: " << m_key.to_string()
		    << "; value: " << m_value.to_string()
		    << "}";
		return out.str();
	}

	bool cache_value::build_index()
	{
		const key_wrapper* key;
		size_t key_bytes;
		const value_wrapper* value;
		size_t value_bytes;
		boost::asio::const_buffer buffer = data();
		while(boost::asio::buffer_size(buffer) > 0)
		{
			key = reinterpret_cast<const key_wrapper*>(boost::asio::buffer_cast<const char*>(buffer));
			key_bytes = key->bytes();
			if(key_bytes > boost::asio::buffer_size(buffer))
			{
				return false;
			}
			buffer = buffer + key_bytes;
				
			value = reinterpret_cast<const value_wrapper*>(boost::asio::buffer_cast<const char*>(buffer));
			value_bytes = value->bytes();
			if(value_bytes > boost::asio::buffer_size(buffer))
			{
				return false;
			}
			buffer = buffer + value_bytes;

			m_block_index.push_back(block_entry(key, value));
		}
		return true;
	}
	

} // namespace xbase
